package com.xiaopeng.common.secure;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * 脱敏加密反序列化
 */
public class DesensitizationDecryptDeSerializer extends JsonDeserializer<Object> implements ContextualDeserializer {

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        // 只针对String类型
//        Desensitization desensitization = property.getAnnotation(Desensitization.class);
//        if (Objects.nonNull(desensitization) && Objects.equals(String.class, property.getType().getRawClass())) {
            return this;
//        }
//        return ctxt.findContextualValueDeserializer(property.getType(), property);
//        return super.deserialize(ctxt,property);
    }

    @Override
    public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        String value = p.getValueAsString();
        String fieldName = p.getCurrentName();
        // 获取配置
        DesensitizationProperties properties = DesensitizationProperties.INSTANCE;
        String encryptFieldName = fieldName + properties.getEncryptFieldSuffix();



        System.out.println("Token: " + p.getText());


        // 获取ObjectMapper配置

        // 获取ObjectMapper配置

        // 获取解析上下文
//        JsonStreamContext context = p.getParsingContext();
//        String parentFieldName = null;
//
//        JsonStreamContext parent1 = context.getParent();
//        Object currentValue = parent1.getCurrentValue();
//        String currentName = parent1.getCurrentName();


//        JsonStreamContext parsingContext = p.getParsingContext();
//        JsonPointer jsonPointer2 = parsingContext.pathAsPointer();
//
//        JsonStreamContext parent = p.getParsingContext().getParent();



        // TODO 每次 p.readValueAsTree 结果都不一样 自带游标？？  会自动上树的上父级走？？？// 是往下走
//        TreeNode treeNode1 = p.readValueAsTree();
//        TreeNode treeNode2 = p.readValueAsTree();
//        TreeNode AAAAA = treeNode2.get("msgEncrypt");
//        TreeNode treeNode3 = p.readValueAsTree();
//        TreeNode treeNode4 = p.readValueAsTree();

//        JsonToken jsonToken = p.currentToken();
//        JsonToken currentToken = p.getCurrentToken();
//        JsonStreamContext parsingContext2 = p.getParsingContext();

//        JsonParser traverse = treeNode1.traverse();
//        JsonParser traverse2 = treeNode2.traverse();
//
//        String text = traverse.getText();

        return value;
    }


}
